package com.twu.biblioteca;

import javax.security.auth.login.FailedLoginException;
import java.util.List;

public class BibliotecaApplication {
    IOHandler io;
    Menu applicationMenu;
    BibliotecaAppData applicationData;

    public BibliotecaApplication(IOHandler io, LibraryInventory libraryInventory, UserList userList){
        this.io = io;
        applicationMenu = new Menu();
        applicationData = new BibliotecaAppData(libraryInventory, userList);
    }


    public void changeIOHandler(IOHandler io){
        this.io = io;
    }

    public BibliotecaAppData getSharedData() {
        return applicationData;
    }

    public void run() {
        io.sendOutput("Welcome to Bangalore Library Biblioteca System");

        while (applicationData.isRunning()) {
            showMenu(applicationMenu, io);
            io.sendOutput("Please enter your selection:");
            try {
                int userOption = io.getInputNumber();
                MenuItem selectedMenuItem = applicationMenu.selectMenuItem(userOption);
                // TODO: menu items can now see the IO streams, consider whether we really need to push to output here still
                io.sendOutput(selectedMenuItem.runMenuItem(applicationData, io));
            }
            catch (InvalidMenuSelectionException e) {
                io.sendOutput(e.getMessage());
            }
            catch (NumberFormatException e) {
                io.sendOutput("Select a valid option!!");
            }
        }
    }

    private void showMenu(Menu applicationMenu, IOHandler io) {
        io.sendOutput("");
        io.sendOutput("Select an option from the following:");
        List<String> menuList = applicationMenu.getMenuContents();
        for (String item : menuList) {
            io.sendOutput(item);
        }
    }

    public int getApplicationMenuLength(){
        return applicationMenu.getMenuLength();
    }

}